package com.easyfile.easyfilemaster.controller;


import com.easyfile.easyfilemaster.entity.base.Result;
import com.easyfile.easyfilemaster.entity.base.ResultFactory;
import com.easyfile.easyfilemaster.exception.InternalServiceException;
import com.easyfile.easyfilemaster.exception.NormalServiceException;
import com.easyfile.easyfilemaster.exception.ServiceException;
import com.easyfile.easyfilemaster.exception.ToRequestLimitsException;
import com.easyfile.easyfilemaster.exception.file.*;
import com.easyfile.easyfilemaster.exception.minio.MinioException;
import com.easyfile.easyfilemaster.exception.user.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.util.stream.Collectors;


/**
 * 异常统一处理
 * @author Chenpeman
 */
@RestControllerAdvice
@Slf4j
public class BaseController {
    /**
     * 处理异常
     *
     * @param e 捕捉到的异常对象
     * @return 返回错误信息给用户
     */
    @ExceptionHandler(ServiceException.class)
    public Result<Void> handleException(Throwable e) {
        if (e instanceof ToRequestLimitsException){
            return ResultFactory.fail(e.getMessage());
        }
       if (e instanceof NormalServiceException){
           return ResultFactory.fail(e.getMessage());
       }
        log.error(e.toString());
       if (e instanceof InternalServiceException){
           ResultFactory.internalError(e.getMessage());
       }
        return ResultFactory.internalError(e.getMessage());
    }


    /**
     *
     * 处理@Valid 验证路径中请求实体校验失败后抛出的异常
     *
     * @param e the e
     * @return the result
     */
    @ExceptionHandler(BindException.class)
    public Result<Void> handleValidatedException(BindException e){
        String message = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
        return ResultFactory.fail(message);
    }

    /**
     * 处理@Validate失败后抛出的异常
     *
     * @param e the e
     * @return the result
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public Result<Void> ConstraintViolationExceptionHandler(ConstraintViolationException e) {
        String message = e.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining());
        return ResultFactory.fail(message);
    }
}
